package be.rivendale.renderer;

import javax.swing.*;
import java.awt.*;

public class RenderingWindow {
    private JFrame frame;
    private Graphics graphics;

    public RenderingWindow(int width, int height, boolean fullScreen) {
        frame = new JFrame();
        frame.setTitle("Raytracer");
        frame.setIgnoreRepaint(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.getRootPane().setPreferredSize(new Dimension(width, height));
        frame.pack();
        frame.setVisible(true);
		Thread.yield();

        frame.createBufferStrategy(2);
        graphics = frame.getBufferStrategy().getDrawGraphics();
    }

    /**
     * Draws the results of the specified screen part onto the backbuffer of the this rendering window.
     * The back buffer is not visible untill the buffers have been {@link #flipBuffers()  flipped}.
     * @param screenPart The screen part to draw on the backbuffer of this window.
     */
    public void drawToBackBuffer(ScreenPart screenPart) {
        Graphics graphics = this.graphics;
        int x = screenPart.getX() + frame.getRootPane().getX();
        int y = screenPart.getY() + frame.getRootPane().getY();
        graphics.drawImage(screenPart.getImage(), x, y, null);
    }

    /**
     * Flips the frontbuffer with the backbuffer and visa versa.
     * This causes the backbuffer to become the visible frontbuffer, and the frontbuffer to become the invisible backbuffer.
     * This technique is well know <a href="http://en.wikipedia.org/wiki/Double_buffering">double buffering</a> technique known as page flipping.
     */
    public void flipBuffers() {
        graphics.dispose();
        frame.getBufferStrategy().show();
        graphics = frame.getBufferStrategy().getDrawGraphics();
    }

    public void clear() {
        graphics.clearRect(0, 0, frame.getWidth(), frame.getHeight());
    }
}
